<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-04 16:53:56
 * @LastEditTime: 2023-10-15 16:26:29
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Http\Services\Pro;


use App\Http\Services\Service;
use App\Models\MpcSummaryStorage;
use App\Repositories\ProOutsourcingPlanDetailRepository;
use App\Repositories\ProOutsourcingPlanRepository;

/**
 * @property ProOutsourcingPlanRepository $repository
 * @property ProOutsourcingPlanDetailRepository $details 
 */
class OutsourcingPlanService extends Service
    {
    public function boot(
        ProOutsourcingPlanRepository $repository,
        ProOutsourcingPlanDetailRepository $details,
    ) {
        $this->repository = $repository;
        $this->details    = $details;
        }

    public function list()
        {
        // DB::enableQueryLog();
        $data = $this->repository->condition(request())->getGrid();
        // dd(DB::getQueryLog());

        return $data;
        }
    public function details()
        {
        $data = $this->details->whereMain_id(request("main_id"))->with("main")->getList()->map(function ($v)
            {
            //库存数据
            $v->quantity = round(MpcSummaryStorage::where([
                'material_id' => $v->material_id,
                'location_id' => $v->main->outfactory->getLocation(1),
                'type_id'     => $v->type_id,
            ])->sum("available_quantity"), 2);
            return $v;
            });

        return $data;
        }

    protected function save()
        {
        $data = request()->toArray();

        return $this->repository->autosave($data);
        }
    protected function delete()
        {
        return $this->repository->whereIn("id", $this->getRequestIds())->get()->filter(function ($v)
            {
            if ($v->product->count() > 0) {
                fail("已做收货！禁止删除！");
                }
            $v->details->filter(function ($vv)
                {
                $vv->delete();
                });
            $v->delete();
            });
        }
    }